//
//  AvaliblePID.m
//  ActiveDeck
//
//  Created by Laura McBride on 9/6/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "AvailablePID.h"
#import "AD_PresentationInfo.h"
#import "GDataXMLNode.h"
#import "HttpRequest.h"

@implementation AvailablePID
@synthesize List_PID, List_BjPID, historyPID, arrayLock;


#pragma mark -
#pragma mark Search for Bonjour Service
#define ACTIVEDECKHISTORYPIDS @"ActiveDeckIDS"

- (void)initialize
{
    arrayLock = [[NSLock alloc] init];
    List_BjPID = [[NSMutableArray alloc] init];
    List_PID = [[NSMutableArray alloc]init]; 
    historyPID = [[NSMutableArray alloc] init];
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *presentationHistory = [prefs objectForKey:ACTIVEDECKHISTORYPIDS];
    
    if (presentationHistory != nil)
    {
        NSMutableArray *presentationHistoryArray = [NSKeyedUnarchiver unarchiveObjectWithData:presentationHistory];
        
        if (presentationHistoryArray != nil)
        {
            historyPID = [[NSMutableArray alloc] initWithArray:presentationHistoryArray];
            NSLog(@"HistoryPID Count :%d" , [historyPID count]);
        } else {
            NSLog(@"No History Available");
        }
    } else {
        NSLog(@"No History Available");
    }
}

- (BOOL)start {
    
    [List_BjPID removeAllObjects];
    
    if(netServiceBrowser != nil) {
        [self stop];
    }
    
    netServiceBrowser = [[NSNetServiceBrowser alloc] init];
    if (!netServiceBrowser) {
        return NO;
    }
    
    netServiceBrowser.delegate = self;
    [netServiceBrowser searchForServicesOfType:@"_activedeck._tcp." inDomain:@""];
    
    return YES;
}

- (void)updateList
{
    [arrayLock lock];
    [List_PID removeAllObjects];
    
    for (AD_PresentationInfo *adBonjour in List_BjPID)
        [List_PID addObject:adBonjour];
    
    if( [List_PID count] > 5)
        return;
    
    for (AD_PresentationInfo *adOld in historyPID)
    {
        BOOL found = FALSE;
        for (AD_PresentationInfo *adNew in List_PID)
        {
            if(adOld.presentationID == adNew.presentationID )
            {
                found = TRUE;
                break;
            }            
        }
        
        if(!found)
            [List_PID addObject:adOld];
    }
    
    NSLog(@"PIDListCount: %d", [List_PID count] );
    [arrayLock unlock];
}

- (void)stop {
    if(netServiceBrowser == nil)
        return;
    
    [netServiceBrowser stop];
    [netServiceBrowser release];
    
    [BonjourServers removeAllObjects];
}

- (void)netService:(NSNetService *)sender didUpdateTXTRecordData:(NSData *)data{
    
    NSString *txt = [[NSString alloc] initWithData:[sender TXTRecordData] encoding:NSUTF8StringEncoding];
    
    NSRange start = [txt rangeOfString:@"="];
    NSString *pid = [txt substringWithRange:NSMakeRange(start.location + 1 , 6 )];
//    [self UpdatePinfo:pid];
    [self performSelectorInBackground:@selector(UpdatePinfo:) withObject:pid];
    
    [txt release];
    [sender release];
}

- (void)UpdatePinfo:(NSString*)presentationID
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    
    AD_PresentationInfo *adPI = [[[AD_PresentationInfo alloc]GetPresentADInfo:presentationID] autorelease];

    if([List_BjPID count] < 1){
        if(adPI){
            [List_BjPID addObject:adPI];
        } 
    }
    else
    {
        BOOL found = FALSE;
        
        for (AD_PresentationInfo *adCurrent in List_BjPID)
        {
            if(adPI.presentationID == adCurrent.presentationID )
            {
                found = TRUE;
                break;
            }
        }
        if (!found & (adPI != nil))
            [List_BjPID addObject:adPI];

    }
    
    NSLog(@"BjID_ListCount: %d", [List_BjPID count] );

    
    //[adPI release];
        
    [pool release];
}


- (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didFindService:(NSNetService *)netService moreComing:(BOOL)moreComing {
    if( ! [BonjourServers containsObject:netService] ){
        [BonjourServers addObject:netService];

        [netService setDelegate:self];
        [netService startMonitoring];
        [netService retain];
    }   
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didRemoveService:(NSNetService *)netService moreComing:(BOOL)moreComing {
    [BonjourServers removeObject:netService];
}

- (BOOL)hasPIDsAvailable{
    [arrayLock lock];
    BOOL hasPIDs = (List_PID && List_PID.count > 0);
    [arrayLock unlock];
    
    return hasPIDs;    
}

- (int)PIDCount{
    [arrayLock lock];
    int pidCount = List_PID.count;
    [arrayLock unlock];
    
    return pidCount;
}

-(void)updateHistoryPID:(NSString *)newEnterPID
{
    AD_PresentationInfo *newPID= [[AD_PresentationInfo alloc] GetPresentADInfo:newEnterPID];
    
    if(newPID){
        newPID.pStatus = 1;
        
        NSLog(@"Pstatus = %d, PID=%d , Pstatus=%@ , pIcon=%@ ", newPID.pStatus, newPID.presentationID, [newPID pName], [newPID iconAddress] );
        
        for (AD_PresentationInfo *adOld in historyPID)
        {
            if (adOld.presentationID  == newPID.presentationID)
            {
                [historyPID removeObject:adOld];
                break;
            }
        }
        
        if([historyPID count] > 0){
            [historyPID insertObject:newPID atIndex:0];
        } else {
            [historyPID addObject:newPID];
        }        
        
        if([historyPID count] > 5)
            [historyPID removeObjectAtIndex:5];
        
        NSLog(@"Save historyCount=%d",[historyPID count]);
        
        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        [prefs setObject:[NSKeyedArchiver archivedDataWithRootObject:historyPID] forKey:ACTIVEDECKHISTORYPIDS];
        [prefs synchronize];
        
        [newPID release];
    }
}

#pragma mark -
#pragma mark Get Presentation Info



- (NSString*)FetchPInfo:(NSString *)PID
{
    NSError *loadError;
    
    NSString *URLInfo = [NSString stringWithFormat:@"%@/%@/%@", [HttpRequest GetSvcURL], @"Config.svc/GetPresentationInfo", PID];
    
    
    NSString *URLContent = [NSString stringWithContentsOfURL:[NSURL URLWithString:URLInfo] encoding:NSUTF8StringEncoding error:&loadError];
    
    return URLContent;
}

- (AD_PresentationInfo*)GetPresInfoObject:(NSString*)presentationID{
    AD_PresentationInfo* pInfoToReturn;
    if ([self hasPIDsAvailable]) {
        [arrayLock lock];
        
        for(AD_PresentationInfo *pInfo in List_PID){
            if([presentationID isEqualToString:[NSString stringWithFormat:@"%d", pInfo.presentationID]]){
                pInfoToReturn = pInfo;
            }
        }
        
        [arrayLock unlock]; 
    }
       
    
    return pInfoToReturn;
}

- (void)dealloc
{
    [netServiceBrowser release];
    [BonjourServers release];
    [List_PID release];
    [List_BjPID release];
    [super dealloc];
}


@end
